import { IMiddleware, Middleware } from '@midwayjs/core'
import { Context, NextFunction } from '@midwayjs/koa'

@Middleware()
export class LoggingMiddleware implements IMiddleware<Context, NextFunction> {
  static getName() {
    return LoggingMiddleware.name
  }

  resolve() {
    return async (ctx: Context, next: NextFunction) => {
      const { path, request, getLogger } = ctx

      // 导出文件和验证码
      const logger = getLogger()
      const ignorePath =
        ['/export', '/captcha'].findIndex(v => path.includes(v)) > -1
      const requestBody =
        request.method === 'GET' ? request.query : request.body || {}

      logger.info('<--- request %j', requestBody)

      try {
        await next()
      } finally {
        // 需要重新从上下文取 body
        logger.info('---> response %j', ignorePath ? {} : ctx.body)
      }
    }
  }

  match(ctx: Context) {
    const isApi = ctx.path.startsWith('/api')

    return isApi
  }
}
